package com.teacher.game.framework.util;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import java.util.HashMap;

/**
 * 渲染缓存系统 - 优化频繁绘制的UI元素
 * 缓存HUD、按钮等静态UI组件，减少重复绘制开销
 */
public class RenderCache {
    
    private static RenderCache instance;
    
    // 缓存存储
    private HashMap<String, CachedElement> cache = new HashMap<>();
    
    // 缓存统计
    private int hitCount = 0;
    private int missCount = 0;
    private int maxCacheSize = 20; // 最大缓存数量
    
    /**
     * 缓存元素类
     */
    private static class CachedElement {
        Bitmap bitmap;
        long lastUsed;
        boolean isDirty;
        
        CachedElement(Bitmap bitmap) {
            this.bitmap = bitmap;
            this.lastUsed = System.currentTimeMillis();
            this.isDirty = false;
        }
        
        void updateUsage() {
            this.lastUsed = System.currentTimeMillis();
        }
    }
    
    /**
     * 单例模式获取实例
     */
    public static synchronized RenderCache getInstance() {
        if (instance == null) {
            instance = new RenderCache();
        }
        return instance;
    }
    
    /**
     * 私有构造函数
     */
    private RenderCache() {
    }
    
    /**
     * 获取或创建缓存的UI元素
     * @param key 缓存键
     * @param width 元素宽度
     * @param height 元素高度
     * @param renderer 渲染器函数
     * @return 缓存的位图
     */
    public Bitmap getCachedElement(String key, int width, int height, ElementRenderer renderer) {
        CachedElement element = cache.get(key);
        
        if (element != null && !element.isDirty) {
            // 缓存命中
            element.updateUsage();
            hitCount++;
            return element.bitmap;
        }
        
        // 缓存未命中或需要重绘
        missCount++;
        
        // 创建新的缓存位图
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        
        // 调用渲染器绘制
        renderer.render(canvas);
        
        // 存储到缓存
        CachedElement newElement = new CachedElement(bitmap);
        cache.put(key, newElement);
        
        // 清理过期缓存
        cleanupCache();
        
        return bitmap;
    }
    
    /**
     * 标记缓存项为脏数据
     * @param key 缓存键
     */
    public void markDirty(String key) {
        CachedElement element = cache.get(key);
        if (element != null) {
            element.isDirty = true;
        }
    }
    
    /**
     * 标记所有缓存为脏数据
     */
    public void markAllDirty() {
        for (CachedElement element : cache.values()) {
            element.isDirty = true;
        }
    }
    
    /**
     * 清理过期缓存
     */
    private void cleanupCache() {
        if (cache.size() <= maxCacheSize) {
            return;
        }
        
        // 找出最久未使用的缓存项
        String oldestKey = null;
        long oldestTime = Long.MAX_VALUE;
        
        for (String key : cache.keySet()) {
            CachedElement element = cache.get(key);
            if (element.lastUsed < oldestTime) {
                oldestTime = element.lastUsed;
                oldestKey = key;
            }
        }
        
        // 移除最久未使用的缓存项
        if (oldestKey != null) {
            CachedElement removed = cache.remove(oldestKey);
            if (removed != null && removed.bitmap != null) {
                removed.bitmap.recycle();
            }
        }
    }
    
    /**
     * 清空所有缓存
     */
    public void clearCache() {
        for (CachedElement element : cache.values()) {
            if (element.bitmap != null) {
                element.bitmap.recycle();
            }
        }
        cache.clear();
        hitCount = 0;
        missCount = 0;
    }
    
    /**
     * 获取缓存统计信息
     * @return 缓存统计字符串
     */
    public String getCacheStats() {
        int total = hitCount + missCount;
        float hitRate = total > 0 ? (hitCount * 100.0f / total) : 0;
        
        return String.format("渲染缓存: %d项, 命中率: %.1f%% (%d/%d)", 
                cache.size(), hitRate, hitCount, total);
    }
    
    /**
     * 获取缓存命中率
     * @return 命中率 (0.0-1.0)
     */
    public float getHitRate() {
        int total = hitCount + missCount;
        return total > 0 ? (hitCount / (float) total) : 0;
    }
    
    /**
     * 元素渲染器接口
     */
    public interface ElementRenderer {
        void render(Canvas canvas);
    }
}